package model

import (
	"errors"

	"github.com/google/uuid"
	"github.com/jinzhu/gorm"
)

// VideoInfo represents a video info
type VideoInfo struct {
	gorm.Model
	Name    string    `json:"name"`
	UUID    uuid.UUID `json:"uuid"`
	UserID  int64     `json:"user_id"`
	FileKey string    `json:"file_key"`
	Hash    string    `json:"hash"`
}

// AddNewVideo add a new Video
func AddNewVideo(videoInfo *VideoInfo) (interface{}, error) {
	GenUUID, err := uuid.NewUUID()
	if err != nil {
		return nil, err
	}
	videoInfo.UUID = GenUUID
	video := db.Save(videoInfo)
	return video.Value, nil
}

// ExistVideoByName check the video name is exist or not
func ExistVideoByName(name string) bool {
	var video VideoInfo
	db.Select("id").Where("name = ?", name).First(&video)
	if video.ID > 0 {
		return true
	}
	return false
}

// GetVideo get a single Video
func GetVideo(VideoID string) (*VideoInfo, error) {
	var Video VideoInfo
	// SELECT * FROM Video WHERE id = VideoID;
	db.First(&Video, VideoID)
	if Video.ID == 0 {
		err := errors.New("no Video found")
		return &VideoInfo{}, err
	}
	return &Video, nil
}

// GetVideoWithUserID get a single Video
func GetVideoWithUserID(userID string) ([]VideoInfo, error) {
	var Video []VideoInfo

	db.Where("user_id = ?", userID).Find(&Video)

	if len(Video) == 0 {
		err := errors.New("no Video found")
		return []VideoInfo{}, err
	}

	return Video, nil
}

// ExistVideoByID check the id is exist or not
func ExistVideoByID(ID int) bool {
	var myVideo VideoInfo
	db.Select("id").Where("id = ?", ID).First(&myVideo)
	if myVideo.ID > 0 {
		return true
	}
	return false
}

// UpdateVideo edit user info
func UpdateVideo(id int, data interface{}) bool {
	db.Model(&VideoInfo{}).Where("id = ?", id).Updates(data)

	return true
}

// DeleteVideo delete the user info from db
func DeleteVideo(id int) bool {
	db.Where("id = ?", id).Delete(&VideoInfo{})

	return true
}

// GetAllVideos get the all Videos info from db
func GetAllVideos() (result []VideoInfo, err error) {
	var myVideo []VideoInfo
	db.Find(&myVideo)

	if len(myVideo) == 0 {
		err = errors.New("no Video found")
		return nil, err
	}
	return myVideo, nil
}
